import json
import os
import re
import shutil
import time

import threadpool
from unipath import FILES, DIRS, Path

api_key = 'fd06d5cdeb404dbcb0dc79312e795a61'
domain = 'http://localhost:8096'
image_root_path = ''
local_path = None
gd_path = None
# 视频文件
video_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm', '.iso', '.m2ts', '.mpg', '.m4v']
# 图片文件
download_type = ['.srt', '.ass', '.jpg', '.nfo', '.sub', '.idx']

error_path = []

last_dir_list = []

mapping_gd_ld = []


# 复制文件到本地
def mirror_copy(source_root_dir_path, target_root_dir_path):
    print(source_root_dir_path)
    print(target_root_dir_path)
    # 获取文件夹下的所有文件
    for item_dir in Path(source_root_dir_path).walk(filter=DIRS):
        for item_file in item_dir.walk(filter=FILES):
            # 替换路径
            target_file_path = Path(item_file.replace(source_root_dir_path, target_root_dir_path))
            # 文件已经存在
            if target_file_path.exists():
                print("[!]  " + target_file_path)
                continue
            try:
                target_file_path.parent.mkdir(True)
                # 视频文件
                if target_file_path.ext.lower() in video_type:
                    print("[+]  " + target_file_path)
                    # 创建新文件
                    # file_stream = open(target_file_path, "wb", buffering=0)
                    # file_stream.close()
                    Path("./scrapy_result/source_move_file.mkv").copy(target_file_path)
                    continue
                # 需要复制的文件
                if target_file_path.ext.lower() in download_type:
                    print("[+]  " + target_file_path)
                    item_file.copy(target_file_path)
            except Exception as ex:
                print("[#] #################")
                print("[#] " + repr(ex))
                print("[#] #################")
                # targer_file_path.rmtree(True)

    for item_dir in Path(source_root_dir_path).listdir():
        # 替换路径
        target_file_path = Path(item_dir.replace(source_root_dir_path, target_root_dir_path))
        # 文件已经存在
        if target_file_path.exists():
            print("[!]  " + target_file_path)
            continue
        try:
            target_file_path.parent.mkdir(True)
            # 视频文件
            if target_file_path.ext.lower() in video_type:
                print("[+]  " + target_file_path)
                # 创建新文件
                # file_stream = open(target_file_path, "wb", buffering=0)
                # file_stream.close()
                Path("./scrapy_result/source_move_file.mkv").copy(target_file_path)
                continue
            # 需要复制的文件
            if target_file_path.ext.lower() in download_type:
                print("[+]  " + target_file_path)
                item_dir.copy(target_file_path)
        except Exception as ex:
            print("[#] #################")
            print("[#] " + repr(ex))
            print("[#] #################")
            # targer_file_path.rmtree(True)


# 修改文件后缀
def edit_ext(param_path):
    # 获取文件夹下的所有文件
    for item in Path(param_path).walk(filter=FILES):
        print("[F]  " + item)
        # 处理文件
        if item.ext.lower() in video_type:
            # 文件名称
            new_file = Path(Path(item).parent, Path(item).stem + '.laoji')
            # 如果存在就跳过
            if not new_file.exists():
                print("[A]  " + new_file)
                # 创建新文件
                file_stream = open(new_file, "wb", buffering=0)
                file_stream.close()
            # 删除旧文件
            item.remove()


# 源文件和目标文件建立关系
def source_relation_targer(source_file_path, targer_file_path):
    source_file = []
    targer_file = []
    result_info = []

    # 所有源文件
    for item in Path(source_file_path).walk(filter=FILES):
        print("[S==>]  " + item)
        if item.ext.lower() in ['.laoji']:
            source_file.append(item)

    # 所有目标文件
    for item in Path(targer_file_path).walk(filter=FILES):
        print("[T]-->" + item)
        if item.ext.lower() in video_type:
            targer_file.append(item)

    for item in source_file:
        for sub_item in targer_file:
            if item.stem == sub_item.stem:
                result_info.append({'source_file': item, 'targer_file': sub_item})
                break
    with open('./scrapy_result/115.json', 'w+', encoding='utf-8') as file:
        file.write(json.dumps(result_info, ensure_ascii=False))


def validate_dir(source_file_path, targer_file_path):
    source_file = []
    targer_file = []
    result_info = []

    # 所有源文件
    for item in Path(source_file_path).listdir():
        print("[==>]  " + item)
        source_file.append(item)

    # 所有目标文件
    for item in Path(targer_file_path).listdir():
        print("[-->]  " + item)
        targer_file.append(item)

    # 查找重复
    for item in targer_file:
        for sub_item in source_file:
            if item.stem == sub_item.stem:
                try:
                    print("[D]-->" + sub_item)
                    # shutil.rmtree(sub_item)
                except Exception as ex:
                    print("[#] #################")
                    print("[#] " + repr(ex))
                    print("[#] " + targer_file_path)
                    print("[#] #################")
                break


# 移动文件夹
def move_file_to_file():
    with open('./scrapy_result/115.json', 'r', encoding='utf-8') as file:
        relation_result = json.load(file)
        # 处理所有的文件
        for item in relation_result:
            try:
                # 如果目标文件不存在就跳过
                if not Path(item['targer_file']).exists():
                    continue
                print(item['targer_file'])
                print(item['source_file'])
                Path(item['targer_file']).move(Path(item['source_file']).parent)
            except Exception as ex:
                print("[#] #################")
                print("[#] " + repr(ex))
                print("[#] #################")


def validate_movie_file(source_file_path):
    error_dir_path = []
    for item in Path(source_file_path).walk(filter=DIRS):
        print("[S==>]  " + item)
        exist_file = False
        for sub_item in item.walk(filter=FILES):
            if sub_item.ext.lower() in video_type:
                exist_file = True
                break
        if not exist_file:
            error_dir_path.append(item)
    print("===================================>")
    print("===================================>")
    for item in error_dir_path:
        print("[E]  " + item)


# 先找到文件夹
def mapping_dir(source_file_path, targer_file_path):
    source_dir = []
    targer_dir = []

    # 所有源文件
    for item in Path(source_file_path).listdir():
        print("[S]  " + item)
        source_dir.append(item)

    # 所有目标文件
    for item in Path(targer_file_path).listdir():
        print("[T]  " + item)
        targer_dir.append(item)

    for item in source_dir:
        for sub_item in targer_dir:
            # 找到映射
            if item.stem == sub_item.stem:
                print("[M]  {} ----> {}".format(item.stem, sub_item.stem))
                print("-----------------------------------------")
                # 做文件映射
                mapping_file(item, sub_item)
                print("-----------------------------------------")
                break


# 建立软连接
def mapping_file(source_file_path, targer_file_path):
    source_file = []
    targer_file = []

    # 清空给所有的软连接
    for item in Path(source_file_path).walk(filter=FILES):
        if item.islink():
            item.remove()

    # 所有源文件
    for item in Path(source_file_path).walk(filter=FILES):
        if item.ext.lower() in ['.laoji']:
            source_file.append(item)

    # 所有目标文件
    for item in Path(targer_file_path).walk(filter=FILES):
        if item.ext.lower() in video_type:
            targer_file.append(item)

    for item in source_file:
        for sub_item in targer_file:
            # 找到映射
            if item.stem == sub_item.stem:
                # 执行命令
                cmd = 'mklink "{0}" "{1}"'.format(Path(item.parent, item.stem + sub_item.ext), sub_item)
                os.system(cmd)
                # if (os.system(cmd)) == 0:
                #     print("执行完成")
                break


# https://www.jb51.net/article/170248.htm
# pip install -r requirements.txt #使用requirements.txt安装依赖的方式：
# pip install pipreqs #安装
# pipreqs . --encoding=utf8 --force # 在当前目录生成
# python .\115-util.py
if __name__ == '__main__':
    # mirror_copy(r'Y:\优蛋网盘\影视剧集\数据工厂\脏数据', r"E:\临时文件\meta-data")
    # validate_dir(r"Y:\优蛋网盘\影视剧集\高清影视", r"Y:\优蛋网盘\我的接收\FRDS已刮削396部")
    # edit_ext(r"E:\临时文件\meta-data")
    # source_relation_targer(r"Y:\优蛋网盘\影视剧集\数据工厂\已处理", r"Y:\优蛋网盘\影视剧集\数据工厂\脏数据")
    # move_file_to_file()
    # validate_movie_file(r"Y:\优蛋网盘\影视剧集\数据工厂\已处理")
    # mapping_dir(r"E:\emby\高清影视", r"Y:\优蛋网盘\影视剧集\高清影视")
    mapping_file(r"E:\emby\高清影视", r"Y:\优蛋网盘\影视剧集\高清影视")
